package com.zmkm.service.impl;

import com.zmkm.common.ServerResponse;
import com.zmkm.dao.Client_informationMapper;
import com.zmkm.dao.ProductMapper;
import com.zmkm.dao.Product_use_registerMapper;
import com.zmkm.entity.Client_information;
import com.zmkm.entity.Product;
import com.zmkm.entity.Product_use_register;
import com.zmkm.service.IProductService;
import com.zmkm.vo.ProductRegister;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service("iProductService")
public class ProductServiceImpl implements IProductService {
	@Autowired
	private Product_use_registerMapper registerMapper;
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private Client_informationMapper clientMapper;

	@Override
	@SuppressWarnings("finally")
	@Transactional(rollbackFor = { RuntimeException.class })
	public ServerResponse ProductUseRegister(ProductRegister pr) {
		boolean Vu = false;
		try {
			Product product = this.productMapper.selectByProductOrModel(pr.getProduct_name(), pr.getProduct_model());
			Product wristband = this.productMapper.selectByProductOrModel(pr.getWristband_name(),pr.getWristband_model());
			
			Client_information ci = new Client_information();
			ci.setNewClient(pr.getClient_name(), pr.getClient_phone(), pr.getVip_number(),pr.getService_stronghold_name(), pr.getUptown_name(), pr.getClient_address());
			this.clientMapper.insertSelective(ci);
			if (ci.getId() <= 0) {
				Vu = false;
				throw new RuntimeException();
			}
			Vu = true;
			Product_use_register register = new Product_use_register();
			register.setNewRegister(pr.getTime(), product.getId(), wristband.getId(),
					Integer.valueOf(pr.getWristband_number()), Integer.valueOf(ci.getId()), ci.getUptown_name(),
					ci.getClient_address(), pr.getInstall_man(), pr.getService_man(), pr.getService_stronghold_name(),
					pr.getRemarks(), pr.getPayment());
			if (this.registerMapper.insertSelective(register) <= 0) {
				Vu = false;
				throw new RuntimeException();
			}
			Vu = true;
		} catch (RuntimeException e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			throw new RuntimeException();
		} finally {
			if (Vu)
				return ServerResponse.createBySuccessMessage("提交成功");
			else
				return ServerResponse.createByErrorMessage("添加失败，请重新添加");
		}
	}

	public List<String> productNameByType(int product_type) {
		return this.productMapper.selectProductNameByType(product_type);
	}

	public List<String> productModel(String productName) {
		return this.productMapper.selectModelByProductName(productName);
	}
}
